package cn.xenoscode.mqttclient.mqtt;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author Xenos
 * @version V1.0
 * @Package xenoscode.cn.mqttpool.pool
 * @date 2020/9/1 16:54
 */
public class SimpleMqttClientCallback implements MqttCallbackExtended {
    private SimpleMqttClient client;
    private int connectTimes = 0;

    public SimpleMqttClientCallback(SimpleMqttClient client) {
        this.client = client;
    }

    @Override
    public void connectComplete(boolean b, String s) {
        System.out.println("————" + client.getClientid() + " 连接成功!————");
        //连接成功后，自动订阅主题
        client.subscribe();
        connectTimes = 0;
    }

    @Override
    public void connectionLost(Throwable throwable) {
        System.out.println("————" + client.getClientid() + " 连接丢失!————");
        //可以在此处做重连处理
        if (connectTimes < client.getMaxConnectTimes()) {
            client.refresh();
            connectTimes++;
        } else {
            client.disconnect();
        }
    }

    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
        LocalDateTime startTime = LocalDateTime.now();
        System.out.println("[MQTT]" + client.getClientid() + " ----成功接收消息！---- 时间： " + startTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")));
        String content = new String(mqttMessage.getPayload());
        System.out.println("接收消息主题 : " + topic);
        System.out.println("接收消息Qos : " + mqttMessage.getQos());
        System.out.println("接收消息内容 : " + content);
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        System.out.println("[MQTT]" + client.getClientid() + "  ----成功发送消息！---- 时间： " + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")));
    }
}
